/**
 * 
 */
package org.mhz.sit.custom;

import javafx.event.EventHandler;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

import org.mhz.sit.entity.Speaker;

/**
 * @author Mahan
 * 
 * Custom JavaFX editing cell
 */
public class EditingCell extends TableCell<Speaker, String>
{
    private TextField textField;

    /**
     * Constructor
     */
    public EditingCell()
    {
    }

    @Override
    public void startEdit()
    {
        super.startEdit();

        if (textField == null)
        {
            createTextField();
        }
        setText(null);
        setGraphic(textField);
        textField.selectAll();
    }

    @Override
    public void cancelEdit()
    {
        super.cancelEdit();

        setText((String) getItem());
        setGraphic(null);
    }

    @Override
    public void updateItem(final String aItem, final boolean aEmpty)
    {
        super.updateItem(aItem, aEmpty);

        if (aEmpty)
        {
            setText(null);
            setGraphic(null);
        }
        else
        {
            if (isEditing())
            {
                if (textField != null)
                {
                    textField.setText(getString());
                }
                setText(null);
                setGraphic(textField);
            }
            else
            {
                setText(getString());
                setGraphic(null);
            }
        }
    }

    /**
     * Create text field
     */
    private void createTextField()
    {

        textField = new TextField(getString());
        textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
        textField.setOnKeyReleased(new EventHandler<KeyEvent>()
        {

            @Override
            public void handle(KeyEvent t)
            {
                if (t.getCode() == KeyCode.ENTER)
                {
                    commitEdit(textField.getText());
                }
                else if (t.getCode() == KeyCode.ESCAPE)
                {
                    cancelEdit();
                }
            }
        });
    }

    /**
     * Get the string
     *
     * @return The string
     */
    private String getString()
    {
        return getItem() == null ? "" : getItem().toString();
    }
}
